<template>
  <div>
    <el-amap
        building-animation="true"
        :vid="amapId"
        :map-style="mapStyle"
        :zooms="zooms"
        :zoom="zoom"
        pitch="50"
        view-mode="3D"
        rotation="-15"
        rotate-enable="true"
        :features='elements'
        :center="center"
        :plugin="plugins"
        :scrollWheel="true"
        ref="amap"
    >
      <el-amap-marker
          v-for="(item, index) in markers"
          :events="item.events"
          :icon="item.icon"
          :position="item.lnglat"
          :key="index"
        
      ></el-amap-marker>
      <el-amap-info-window
          v-if="window"
          
          retainWhenClose="true"
          :position="window.position"
          :visible="window.visible"
          :content="window.content"
          :offset="window.offset"
          :isCustom="true"
          @close="infoWindowClose"
      ></el-amap-info-window>
      <!-- <el-amap-polygon
          v-for="(poly, i) in pathPolygon"
          :path="poly"
          fillOpacity="0"
          :key="'polygon_list' + i"
          strokeColor="blue"
          strokeOpacity="1"
          strokeStyle="dashed"
      ></el-amap-polygon> -->
    </el-amap>
  </div>
</template>
<script>
import mark_b from './img/device_b.svg'
// import mark_r from './img/device_r.svg'
// import mark_b from './img/gateway.svg'
import create from '../core/echart/create'

export default create({
  name: 'Dmap',
  data(){
    return {
      markers: [],
      labels: [],
      deviceIdList: [],
      pathPolygon: [],
      windows:[],
      window: {
        position: [0,0],
        visible: false,
        content: '',
        offset: [0,-18]
      },
      sub: '',
      subProperties: '',
      subEvents: '',
      payloadPropertiesValue: {},
      payloadEventsValue: {},
      plugins: [
          // {
          //   pName: 'ToolBar',
          //   position: "RT",
          //   events: {
          //     init (o) {
          //       console.log(o)
          //     }
          //   }
          // }
      ]
    }
  },
  computed: {
    mapStyle(){
      return 'amap://styles/' + this.option.mapStyle
    },
    lng(){
      console.log(this.option.lng)
      return this.option.lng || 106.557297
    },
    lat(){
      return this.option.lat || 29.542191
    },
    center(){
      return [this.lng, this.lat]
    },
    zoom(){
      return this.option.zoom || 15;
    },
    zooms(){
      return [this.option.zoomsMin, this.option.zoomsMax] || [3, 20];
    },
    amapId(){
      return 'main_' + new Date().getTime();
    },
    elements(){
      return this.option.elements || ["bg", "road", "point", "building"];
    },
    markImg(){
      return this.option.markImg || mark_b
    },

    markerQueryParam() {
     
      try {
        return eval(this.option.markerQueryParam)
      } catch (error) {
        console.warn(error)
        return () => {}
      }
    },
    markerConfig() {
     
      try {
        return eval(this.option.markerConfig)
      } catch (error) {
        console.warn(error)
        return () => {}
      }
    },
    infoWindowConfig() {
      
      try {
        return eval(this.option.infoWindowConfig)
      } catch (error) {
        console.warn(error)
        return () => {}
      }
    }
  },
  mounted() {
    this.getNotDeviceList();
    this.getDeviceList().then(() => {
      // this.getRealTimeDeviceInfo();
    })
  },
  methods:{
    //获取边界点
    getNotDeviceList(){
      window.axios({
        url: '/jetlinks/geo/object/_search/geo.json',
        method: 'POST',
        data: {
          'filter': {
            'where': 'objectType not device',
            'pageSize': 1000
          }
        }
      }).then(res => {
        const data = res.data.result;
        data.features.map((item) => {
          item.geometry.coordinates.map((path) => {
            this.pathPolygon.push(path[0]);
          });
        });
      })
    },
    getDeviceList(){
      let _this = this
      let param = undefined

      if(this.markerQueryParam) {
        param = this.markerQueryParam()
      }

      return new Promise((resolve, reject) => {
        window.axios({
          url: '/jetlinks/geo/object/_search/geo.json',
          method: 'POST',
          data: {
            'filter': {
              'where': 'objectType = device',
              'pageSize': 1000
            },
            shape: {
              objectId: 'sxjq',
            },
            ...param
          }
        }).then(res => {
          if(res.status == 200){
            const data = res.data.result;
            const list = data.features
            if(param && param.shape.objectId === 'sxjd') {
                let _config = {}
                
                if(this.markerConfig) {
                  _config = this.markerConfig(list[0], this.$refs.amap.$$getInstance())
                }
                this.markers.push({
                  
                  lnglat: list[0].geometry.coordinates,
                  deviceInfo: list[0].properties,
                  icon: this.markImg || mark_b,
                  events: {
                    click() {
                      const axiosList = list.map(a => window.axios.get('/jetlinks/device/instance/'+a.properties.objectId+'/detail'))
                      window.axios.all(axiosList).then(window.axios.spread((...resultList) => {
                          console.log(resultList)
                          const dataArr = resultList.filter(_a => _a.status === 200).map(b => {
                            const result = b.data.result
                            const img = result.tags.find(c => c.key === 'img')
                            return {
                              name: result.name,
                              state: result.state,
                              img: img ? img.value : ''
                            }
                          })
                            
                            let _infoConfig = undefined
                            if(dataArr && _this.infoWindowConfig) {
                              _infoConfig = _this.infoWindowConfig(dataArr, _this.$refs.amap.$$getInstance())
                            }
                            
                            _this.windows.forEach(i => {
                              i.visible = false; //关闭窗体
                            });
                            
                            if(_infoConfig) {
                              _this.$nextTick(() => {
                                _this.window.content = _this._createInfoWindow(_infoConfig)
                                _this.window.position = list[0].geometry.coordinates
                                _this.window.visible = true
                              })
                            }
                      }))
                    }
                  },
                  ..._config,
                });
                this.deviceIdList.push(list[0].properties.objectId);
                this.windows.push({
                  position: list[0].geometry.coordinates,
                  content: '<div>没得信息</div>',//内容
                  offset:[5,-20],//窗体偏移
                  visible: false
                })
            } else {
              list.map((item, index) => {
                let _config = {}
                
                if(this.markerConfig) {
                  _config = this.markerConfig(item, this.$refs.amap.$$getInstance())
                }
                this.markers.push({
                  
                  lnglat: item.geometry.coordinates,
                  deviceInfo: item.properties,
                  icon: this.markImg || mark_b,
                  events: {
                    click() {
                      
                      window.axios({
                        url: '/jetlinks/device/instance/'+item.properties.objectId+'/detail',
                        method: 'GET'
                      }).then((res) => {
                        if(res.status === 200){
                          console.log(res.data.result)
                          let _infoConfig = undefined
                          if(_this.infoWindowConfig) {
                            _infoConfig = _this.infoWindowConfig(res.data.result, _this.$refs.amap.$$getInstance())
                          }
                          
                          _this.windows.forEach(i => {
                            i.visible = false; //关闭窗体
                          });
                          
                          if(_infoConfig) {
                            _this.$nextTick(() => {
                              _this.window.content = _this._createInfoWindow(_infoConfig)
                              _this.window.position = item.geometry.coordinates
                              _this.window.visible = true
                            })
                          }
                        }
                      })
                    }
                  },
                  ..._config,
                });
                this.deviceIdList.push(item.properties.objectId);
                this.windows.push({
                  position: item.geometry.coordinates,
                  content: '<div>没得信息</div>',//内容
                  offset:[5,-20],//窗体偏移
                  visible: false
                })
              });

            }


            
            resolve();
          }else{
            reject(res)
          }
        })
      })
    },
    infoWindowClose() {
      console.log(this.window)
      this.window.visible = false
    },
    // getRealTimeDeviceInfo(){
    //   this.sub = window.getWebSocket("location-info-status-by-array-deviceId",
    //       "/device-current-state", {
    //         "deviceId": this.deviceIdList
    //       }).subscribe((resp) => {
    //     const {payload} = resp;
    //     let key = Object.keys(payload)[0]
    //     this.markers.forEach(item => {
    //       if(key == item.deviceInfo.objectId){
    //         item.icon = this.markImg   //payload[key] === 'online' ? mark_b : mark_r;
    //       }
    //     })
    //   })
    // },
    getRealTimeProperties(deviceId, productId){
      this.subProperties = window.getWebSocket(
          "location-info-property-" + deviceId,
          "/dashboard/device/"+productId+"/properties/realTime", {
            deviceId: deviceId,
            history:1
          }).subscribe((resp) => {
        const {payload} = resp;
        this.payloadPropertiesValue = payload.value
      })
    },
    getRealTimeEvent(deviceId, productId){
      this.subEvents = window.getWebSocket(
          "location-info-event-" + deviceId + '-' + productId,
          "/dashboard/device/"+productId+"/events/realTime", {
            deviceId: deviceId,
            history:1
          }).subscribe((resp) => {
        const {payload} = resp;
        this.payloadEventsValue = payload.value
      })
    },
    _createInfoWindow(config) {
      const infoBody = document.createElement('div')
      const infoCloseBtn = document.createElement('div')
      const infoTitle = document.createElement('div')
      const infoTitleText = document.createElement('div')
      const _this = this
      infoCloseBtn.innerHTML = '×'
      
      infoBody.className = 'jetlinks-amap-infowindow'
      infoTitle.className = 'jetlinks-amap-infowindow-infoTitle'
      infoCloseBtn.className = 'jetlinks-amap-infowindow-close'

      infoTitleText.innerHTML = config.title || ''
      infoTitle.appendChild(infoTitleText)
      infoTitle.appendChild(infoCloseBtn)

      infoBody.style = {...infoBody.style,...config.bodyStyle}
      infoCloseBtn.style = {...infoCloseBtn.style,...config.closeBtnStyle}
      
      _this.updateStyle(infoBody,config.bodyStyle)
      _this.updateStyle(infoTitle,config.infoTitleStyle)
      _this.updateStyle(infoCloseBtn,config.closeBtnStyle)
      _this.updateStyle(infoTitleText,config.titleTextStyle)

      
      infoCloseBtn.onclick = () => {
        _this.window.visible = false
      }
      
      if(config.content) {
        infoBody.innerHTML = config.content
      }
      infoBody.insertBefore(infoTitle,infoBody.childNodes[0])

      return infoBody
    },
    updateStyle(dom, style) {
      for (const key in style) {
        dom.style[key] = style[key]
      }
    },
    createInfoWindow(deviceName, status, productId, productName, properties, event){
      return `<div class="window-box">
        <div style="display: flex;width: 100%;height: 60px;color: white;">
          <div style="display: flex;justify-content: center; width: 80px;height: 50px;">
            <img style="width: 50px;height: 50px;" src=""/>
          </div>
          <div style="width: 300px; font-size: 12px;">
            <div style="display: flex;width: 100%;justify-content: space-around;height: 25px;line-height: 25px;">
              <div style="font-size: 14px; font-weight: 600;">${deviceName}</div>
              ${status == '离线' ? `<div style="color: red;">${status}</div>` : `<div style="color: green;">${status}</div>`}
            </div>
            <div style="display: flex;width: 100%;justify-content: space-around;height: 25px;line-height: 25px;">
              <div>ID: ${productId}</div>
              <div>产品： ${productName}</div>
            </div>
          </div>
        </div>
        <div style="width: 100%;">
          ${properties.map(i => `<div v-for="item in metadata" class="box-item">
              <div style="display: flex">
                <div class="box-title">${i.name}</div>
                <div>${this.payloadPropertiesValue.propertyName == i.name ? this.payloadPropertiesValue.formatValue : '/'}</div>
              </div>
            </div>`).join('')}
           ${event.map(i => `<div v-for="item in metadata" class="box-item">
              <div style="display: flex">
                <div class="box-title">${i.name}</div>
                <div>${this.payloadEventsValue.propertyName == i.name ? this.payloadEventsValue.formatValue : '/'}</div>
              </div>
            </div>`).join('')}
        </div>
      </div>`
    },
    mapClick() {
      console.log(this.dataFormatter)
    }
  },
  destroyed(){
    // this.sub && this.sub.unsubscribe();
    this.subProperties && this.subProperties.unsubscribe();
    this.subEvents && this.subEvents.unsubscribe();
  },
})
</script>

<style>
.jetlinks-amap-infowindow {
  background-color: #fff;
  min-width: 200px;
  border-radius: 4px;
  box-shadow: 0 0 12px rgba(0,0,0,.4);
}
.jetlinks-amap-infowindow-infoTitle {
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.jetlinks-amap-infowindow-close {
  color: rgba(0,0,0,.45);
  font-size: 20px;
}
</style>
